package game;

import misc.Vector3i;
import player.ComputerPlayer;
import player.Player;
import player.HumanPlayer;
import action.MoveAction;
import character.Character;
import com.jme3.math.FastMath;
import java.util.LinkedList;
import java.util.List;

public abstract class TurnController {
    public static final boolean takeTurnsResolving = true;
    protected static List<Player> players = new LinkedList<Player>();
    protected static int nextPlayerIndex = 0;
    protected static Player currentPlayer;

    public static void nextTurn() {
	currentPlayer = players.get(nextPlayerIndex);
	System.out.println("Starting turn for player: "+currentPlayer.getName());
	nextPlayerIndex++;

	if(currentPlayer instanceof HumanPlayer) {
	    if(!StateController.getTurnAppState().isTurnInputHandlerAttached())
		StateController.getTurnAppState().attachTurnInputHandler();
	} else {
	    if(StateController.getTurnAppState().isTurnInputHandlerAttached())
		StateController.getTurnAppState().detachTurnInputHandler();
	    Character character = ((ComputerPlayer)currentPlayer).getCharacter();
	    for(int i=0;i<5;i++) {
                List<Vector3i> validMoveLocations = character.getValidMoveLocations();
		character.getActionQueue().queueActionLast(new MoveAction(character, validMoveLocations.get(FastMath.rand.nextInt(validMoveLocations.size()))));
            }
	    endCurrentTurn();
	}
    }

    public static void endCurrentTurn() {
	if(nextPlayerIndex >= players.size()) {
	    nextPlayerIndex = 0;
	}
	if(takeTurnsResolving || (!takeTurnsResolving && nextPlayerIndex == 0)) {
            StateController.turnEnded();
        } else {
	    nextTurn();
        }
    }

    public static void addPlayer(Player player) {
	players.add(player);
    }

    public static Player getPlayer(int playerId) {
	for(Player player : players)
	    if(player.getId() == playerId)
		return player;
	return null;
    }

    public static Player getCurrentPlayer() {
	return currentPlayer;
    }

    public static HumanPlayer getCurrentHumanPlayer() {
	return (HumanPlayer)currentPlayer;
    }
}
